import { OrgTree } from '@/pages/organization/components/tree';
import { UserRole } from '@/pages/user/components/role';
import { Divider } from 'antd';
import { GFormSchema, GTable, GTableSchema } from 'geminis-react';
import { useCallback, useRef } from 'react';
import styles from '../organization/components/tree.less';
import { OrgSelectModal } from '@/pages/organization/components/tree-select';
import services from '@/services/user';

const { move2Org } = services.UserController;

export default () => {
  const tree = useRef<any>();
  const table = useRef<any>();

  const onTreeSelected = useCallback(({ selectedKeys }: any) => {
      table.current.loadData({ organizationId: selectedKeys[0] });
    },
    [table],
  );

  const setOrganizationId = useCallback((value: any, schema: GFormSchema) => {
    schema.data = {
      url:
        '/api/resources/user/org/' +
        tree.current.selection.selectedKeys[0] +
        '/属于',
    };
  }, []);

  const tableReload = useCallback(() => {
    table.current.loadData({ organizationId: tree.current.selection.selectedKeys[0] });
  }, []);

  const moveUser2Org = useCallback((userId: string, selection: any) => {
    move2Org(userId, selection.selectedKeys[0])
      .then(() => {
        tableReload();
      });
  }, []);

  const schema: GTableSchema = {
    headerTitle: '用户信息',
    data: {
      url: '/api/resources/user',
      include: ['roles'],
      sort: ['name:asc'],
    },
    manualRequest: true,
    action: {
      toolbar: {
        add: {
          form: {
            schemaPath: '/resources-pc/schema/user/edit.json',
            onSubmitting: setOrganizationId,
          },
        },
      },
      row: {
        edit: {
          form: {
            schema: {
              data: {
                url: '/api/resources/user',
              },
            },
          },
        },
        delete: true,
        render: (record: any) => [
          <UserRole key={'role-' + record.id} user={record} onSubmitted={tableReload} />,
          <OrgSelectModal key={'org-' + record.id} text="移动"
                          onOk={(selection) => moveUser2Org(record.id, selection)} />,
        ],
      },
    },
  };

  return (
    <div className={styles.main}>
      <div className={styles.tree}>
        <OrgTree ref={tree} onSelected={onTreeSelected} />
      </div>
      <Divider type="vertical" className={styles.fullHeight} />
      <div className={styles.content}>
        <GTable
          ref={table}
          schema={schema}
          schemaPath="/resources-pc/schema/user/table.json"
        />
      </div>
    </div>
  );
};
